package com.dps.omc.schedule;

import com.dps.omc.monitor.AgentMonitor;
import com.dps.omc.monitor.AgentState;
import com.dps.omc.monitor.utils.MonitorConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by lip on 2016-05-30.
 */
@Service
public class MonitorTask extends BaseTask{

    @Autowired
    private AgentMonitor agentMonitor;

    public void execute() throws Exception {
        logInfo("MonitorTask任务开始");

        Map<String,AgentState> map = agentMonitor.getMap();
        Set<String> set = map.keySet();
        for(String key:set)
        {
            AgentState agentState = map.get(key);
            boolean res = monitorAgent(agentState.getIp(), MonitorConstants.PORT);
            if(res)
            {
                agentState.up();
            }
            else
            {
                agentState.down();
            }
        }

        logInfo("MonitorTask任务结束");
    }

    public Boolean monitorAgent(String ip, int port) {
        try {
            // 创建jmx连接
            JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi://" + ip+ ":" + port + "/jndi/rmi://" + ip + ":" + port + "/server");
//			System.out.println(jmxUrl);
            Map<String, Object> map = new HashMap<String, Object>();
            JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, map);
            // 获得MBean服务连接
            MBeanServerConnection mbsConn = jmxConn.getMBeanServerConnection();
            String defaultDedomain = mbsConn.getDefaultDomain();
            ObjectName objname = new ObjectName(defaultDedomain+ ":name=monitorService");
            Object str = mbsConn.invoke(objname, "outPutData", null, null);// 调用服务端的方法
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        MonitorTask task = new MonitorTask();
        boolean res = task.monitorAgent("10.238.14.178",40000);
        System.out.println(res);
    }
}
